﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CTRL;
using GUI.Utilities;
using BLL;
using GUI.UserInterfaces;
using UTIL;

namespace GUI.UserControls
{
    public partial class UCListJumpers : UserControl
    {
        private CtrlJumper ctrlJumper;
        private List<Jumper> jumperList;

        public UCListJumpers()
        {
            InitializeComponent();

            ctrlJumper = CtrlJumper.Instance;
            jumperList = new List<Jumper>();

            txtSearch.PlaceholderText = "Search for a jumper...";

            foreach (var j in ctrlJumper.GetJumpers())
            {
                if (!j.Name.Equals("n/a"))
                {
                    jumperList.Add(j);
                }
            }

            PopulateList(jumperList);
        }

        private void PopulateList(List<Jumper> list)
        {
            listJumpers.Items.Clear();

            foreach (var j in list)
            {
                listJumpers.Items.Add(new ListBoxItem(j.Country.TLD, j.Name));
            }
        }

        private void listJumpers_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListBoxItem selected = (ListBoxItem)listJumpers.SelectedItem;
            Jumper jumper = ctrlJumper.GetJumpers().FirstOrDefault(x => x.Name.Equals(selected.Text));

            this.lblName.Text = jumper.Name;
            this.lblCountry.Text = jumper.Country.Name;
            this.lblCurrent.Text = jumper.Current.ToString();
            this.lblTotal.Text = jumper.Total.ToString();
            this.lblRank.Text = String.Format("{0} of {1}", jumper.Rank, ctrlJumper.GetJumpers().Count - 1);
            this.picFlag.Image = (Image)GUI.Properties.Resources.ResourceManager.GetObject("flag_" + jumper.Country.TLD);
        }

        private void txtSearch_TextChanged(object sender, EventArgs e)
        {
            if (txtSearch.TextLength > 0)
            {
                var searchList = jumperList.Where(x => x.Name.ToLower().Contains(txtSearch.Text.ToLower())).OrderBy(x => x.Name).ToList();

                PopulateList(searchList);
            }
            else
            {
                PopulateList(jumperList);
            }
        }
    }
}
